package com.dhh.web.modules.user.service.impl;

import com.dhh.web.common.exception.BusinessException;
import com.dhh.web.common.shiro.ShiroUtils;
import com.dhh.web.common.utils.RandomUtil;
import com.dhh.web.modules.user.domain.Role;
import com.dhh.web.modules.user.domain.User;
import com.dhh.web.modules.user.repo.RoleRepo;
import com.dhh.web.modules.user.repo.UserRepo;
import com.dhh.web.modules.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;

import static com.dhh.web.common.utils.UserConst.NORMAL_USER;

/**
 * @Auther: dhh
 * @Date: 2018/11/23 09:33
 * @Email: fzlinjianhui@163.com
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepo userRepo;
    @Autowired
    private RoleRepo roleRepo;

    @Override
    public User save(User user) {
        Role normalUser = roleRepo.findByRoleCode(NORMAL_USER).orElseThrow(() -> new BusinessException("根据编码:" + NORMAL_USER + "找不到角色"));
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String password = ShiroUtils.sha256(user.getPassword(), salt);
        user.setSalt(salt);
        user.setPassword(password);
        user.setStatus(1);
        user.setUserId(RandomUtil.randomUUID());
        user.setRoles(new HashSet<Role>(){{add(normalUser);}});
        return userRepo.save(user);
    }

    @Override
    public void delete(String id) {
        userRepo.deleteById(id);
    }

    @Override
    public Page<User> findByPage(Pageable pageable) {
        return userRepo.findAll(pageable);
    }

    @Override
    public List<User> findAll() {
        return userRepo.findAll();
    }

    @Override
    public User findById(String id) {
        return userRepo.findById(id).orElseThrow(()->new BusinessException("根据id"+id+"没找到相关用户信息"));
    }

    @Override
    public Optional<User> findByUsername(String username) {
        return userRepo.findByUsername(username);
    }
}
